<template>
  <el-dialog
    :title="title"
    :visible.sync="value"
    append-to-body
    @close="closeDialog"
    @open="openDialog"
  >
    <el-form
      ref="form"
      :model="form"
      label-width="100px"
      :rules="formRules"
      :disabled="type === 'view'"
    >
      <el-form-item label="模板名称" prop="templateName">
        <el-input v-model="form.templateName"></el-input>
      </el-form-item>
      <el-form-item label="计费类型" prop="templateType">
        <el-select v-model="form.templateType" @change="templateTypeHandler">
          <el-option label="电费" value="1"></el-option>
          <!-- <el-option label="水费" value="2"></el-option> -->
        </el-select>
      </el-form-item>
      <el-form-item label="费用组合">
        <el-checkbox-group v-model="form.checkList">
          <el-checkbox label="基本费用" disabled></el-checkbox>
          <el-checkbox label="其他费用"></el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="计费模式" prop="templateMode">
        <el-select v-model="form.feeType">
          <el-option label="平均" :value="1"></el-option>
          <el-option label="峰谷" :value="2"></el-option>
          <el-option label="阶梯" :value="3"></el-option>
          <el-option label="月平均价" :value="4"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="结算周期" prop="settlementCycle">
        <el-input type="number" :min="0" v-model="form.settlementCycle">
          <template slot="append">天</template>
        </el-input>
      </el-form-item>
      <el-form-item
        label="结算时间"
        v-if="form.feeType != 2"
        prop="settlementTime"
      >
        <el-date-picker
          v-model="form.settlementTime"
          type="datetime"
          placeholder="选择日期时间"
          format="yyyy-MM-dd HH:mm"
          value-format="yyyy-MM-dd HH:mm"
        ></el-date-picker>
      </el-form-item>
      <el-form-item
        v-if="form.templateType === '1' && form.feeType != 3"
        label="单价"
        :prop="`peaklist.${0}.price`"
        :rules="
          form.feeType === 1 && [
            {
              required: true,
              message: '单价不能为空',
              trigger: 'blur',
            },
            ...rechageExg,
          ]
        "
      >
        <el-input
          v-if="form.feeType === 1"
          v-model="form.peaklist[0].price"
          placeholder="请输入单价"
        >
          <template slot="append">元/度</template>
        </el-input>
        <div v-if="form.feeType === 2">
          <el-form-item
            label="尖电价"
            label-width="80px"
            class="item-margin"
            :prop="`valleylist.${0}.ratePrice`"
            :rules="[
              {
                required: true,
                message: '尖电价不能为空',
                trigger: 'blur',
              },
              ...rechageExg,
            ]"
          >
            <el-input
              type="number"
              :min="0"
              placeholder="请输入尖电价"
              v-model="form.valleylist[0].ratePrice"
            >
              <template slot="append">元/度</template>
            </el-input>
          </el-form-item>
          <el-form-item
            label="峰电价"
            label-width="80px"
            class="item-margin"
            :prop="`valleylist.${1}.ratePrice`"
            :rules="[
              {
                required: true,
                message: '峰电价不能为空',
                trigger: 'blur',
              },
              ...rechageExg,
            ]"
          >
            <el-input
              type="number"
              :min="0"
              placeholder="请输入峰电价"
              v-model="form.valleylist[1].ratePrice"
            >
              <template slot="append">元/度</template>
            </el-input>
          </el-form-item>
          <el-form-item
            label="平电价"
            label-width="80px"
            class="item-margin"
            :prop="`valleylist.${2}.ratePrice`"
            :rules="[
              {
                required: true,
                message: '平电价不能为空',
                trigger: 'blur',
              },
              ...rechageExg,
            ]"
          >
            <el-input
              type="number"
              :min="0"
              placeholder="请输入平电价"
              v-model="form.valleylist[2].ratePrice"
            >
              <template slot="append">元/度</template>
            </el-input>
          </el-form-item>
          <el-form-item
            label="谷电价"
            label-width="80px"
            class="item-margin"
            :prop="`valleylist.${3}.ratePrice`"
            :rules="[
              {
                required: true,
                message: '谷电价不能为空',
                trigger: 'blur',
              },
              ...rechageExg,
            ]"
          >
            <el-input
              type="number"
              :min="0"
              placeholder="请输入谷电价"
              v-model="form.valleylist[3].ratePrice"
            >
              <template slot="append">元/度</template>
            </el-input>
          </el-form-item>
        </div>
        <div v-if="form.feeType === 4">
          <el-row :gutter="10">
            <el-col
              :span="5"
              v-for="(month, index) in form.averagePriceList"
              :key="month.averageMouth"
            >
              <span style="display: block"
                ><i style="color: red">*</i
                >{{ `${month.averageMouth}月` }}</span
              >
              <el-form-item
                class="item-margin"
                :prop="`averagePriceList.${index}.price`"
                :rules="[
                  {
                    required: true,
                    message: '单价不能为空',
                    trigger: 'blur',
                  },
                  ...rechageExg,
                ]"
              >
                <el-input
                  type="number"
                  :disabled="type === 'edit' && index < now_month"
                  :min="0"
                  placeholder="请输入单价"
                  v-model="month.price"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form-item>
      <div v-if="form.feeType === 3" class="ladder-wrapper">
        <div class="label-title">计费单价</div>
        <p class="title-list">
          <span>序号</span>
          <span>起始读数(不含)／度</span>
          <span>终止读数(含)／度</span>
          <span>价格／元</span>
          <span>操作</span>
        </p>
        <div
          v-for="(item, index) in form.peaklist"
          :key="index"
          class="flex"
          style="margin-bottom: 24px"
        >
          <span class="flex-wrap-1 flex flex-center">{{ index + 1 }}</span>
          <el-form-item class="flex-wrap-1" label-width="0px">
            <el-input
              disabled
              :value="index === 0 ? 0 : form.peaklist[index - 1].ladder_data"
              placeholder="起始读数"
            ></el-input>
          </el-form-item>
          <el-form-item
            class="flex-wrap-1"
            label-width="0px"
            :prop="`peaklist.${index}.ladder_data`"
            :rules="
              index != form.peaklist.length - 1 && {
                required: true,
                message: '终止读数不能为空',
              }
            "
          >
            <el-input
              v-if="index != form.peaklist.length - 1"
              v-model="item.ladder_data"
              placeholder="终止读数"
            ></el-input>
          </el-form-item>
          <el-form-item
            class="flex-wrap-1"
            label-width="0px"
            :prop="`peaklist.${index}.price`"
            :rules="[
              {
                required: true,
                message: '单价不能为空',
              },
              ...rechageExg,
            ]"
          >
            <el-input v-model="item.price" placeholder="单价"></el-input>
          </el-form-item>
          <p class="flex-wrap-1 flex flex-center">
            <el-button
              type="text"
              v-if="index === form.peaklist.length - 1"
              @click="addPrice"
              >增加</el-button
            >
            <el-divider
              direction="vertical"
              v-if="
                index === form.peaklist.length - 1 && index != 0 && index != 1
              "
            ></el-divider>
            <el-button
              type="text"
              v-if="index != 0 && index != 1"
              @click="remocePrice(index)"
              >删除</el-button
            >
          </p>
        </div>
      </div>
      <el-form-item
        v-if="form.checkList.includes('其他费用')"
        label="其他费用"
        prop="templatePrice"
      >
        <p class="price-label">
          此费用单独收取，属于服务费，如无需求，请勿勾选
        </p>
        <el-row :gutter="20">
          <el-col :span="12">
            费用名
            <el-input
              v-model="form.otherFee"
              placeholder="请输入费用名"
            ></el-input>
          </el-col>
          <el-col :span="12">
            价格
            <el-input v-model="form.otherFeePrice" placeholder="请输入价格">
              <template slot="append">{{
                form.templateType === "2" ? "元/吨" : "元/度"
              }}</template>
            </el-input>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button v-if="type != 'view'" @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="submitHandle" :loading="submitLoading"
        >确 定</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
import { add, getDetail, update } from "@/api/meter/calculationtemplate";
export default {
  name: "add-template",
  props: {
    ids: {
      type: String,
    },
    type: {
      type: String,
      default: "add",
    },
    value: {
      type: Boolean,
      default: false,
    },
    onLoad: {
      type: Function,
    },
  },
  data() {
    return {
      now_month: new Date().getMonth(),
      form: {
        templateType: "1",
        checkList: ["基本费用"],
        templateMode: "1",
        templateType: "1",
        settlementCycle: "",
        settlementTime: "",
        feeType: 1,
        averagePriceList: [
          {
            averageMouth: 1,
            price: "",
          },
          {
            averageMouth: 2,
            price: "",
          },
          {
            averageMouth: 3,
            price: "",
          },
          {
            averageMouth: 4,
            price: "",
          },
          {
            averageMouth: 5,
            price: "",
          },
          {
            averageMouth: 6,
            price: "",
          },
          {
            averageMouth: 7,
            price: "",
          },
          {
            averageMouth: 8,
            price: "",
          },
          {
            averageMouth: 9,
            price: "",
          },
          {
            averageMouth: 10,
            price: "",
          },
          {
            averageMouth: 11,
            price: "",
          },
          {
            averageMouth: 12,
            price: "",
          },
        ], // 月平均价
        valleylist: [
          {
            rateType: 0,
            ratePrice: "",
          },
          {
            rateType: 1,
            ratePrice: "",
          },
          {
            rateType: 2,
            ratePrice: "",
          },
          {
            rateType: 3,
            ratePrice: "",
          },
        ], // 峰谷列表
        peaklist: [
          {
            ladder: 0,
            ladder_data: "",
            price: "",
          },
          {
            ladder: "",
            ladder_data: "",
            price: "",
          },
        ], // 阶梯价格
      },
      formRules: {
        templateName: [
          { required: true, message: "请选择模板名称", trigger: "blur" },
        ],
        templateType: [
          { required: true, message: "请选择计费类型", trigger: "blur" },
        ],
        templateMode: [
          { required: true, message: "请选择计费模式", trigger: "blur" },
        ],
        settlementCycle: [
          { required: true, message: "请填写结算周期", trigger: "blur" },
        ],
        settlementTime: [
          { required: true, message: "请填写结算时间", trigger: "blur" },
        ],
      },
      submitLoading: false,
      rechageExg: [
        {
          type: "number",
          validator: (rule, value, callback) => {
            if (!Number(value) || !/^\d+(\.\d{1,2})?$/.test(value)) {
              callback(new Error("请填写少于两位小数"));
            }
            callback();
          },
        },
      ],
    };
  },
  computed: {
    title() {
      const { type } = this;
      if (type === "add") {
        return "新增计费模板";
      } else if (type === "edit") {
        return "修改计费模板";
      } else if (type === "view") {
        return "查看计费模板";
      } else {
        return "模板";
      }
    },
  },
  methods: {
    addPrice() {
      let peak = this.form.peaklist;
      peak.push({
        ladder: "",
        ladder_data: "",
        price: "",
      });
      this.$set(this.form, "peaklist", peak);
    },
    remocePrice(index) {
      this.form.peaklist.splice(index, 1);
    },
    openDialog() {
      if (this.type != "add") {
        getDetail(this.ids).then((res) => {
          const data = res.data.data;
          console.log(data);
          this.form = {
            templateName: data.templateName,
            checkList: ["基本费用"],
            templateMode: "1",
            templateType: "1",
            settlementCycle: data.settlementCycle,
            settlementTime: data.settlementTime,
            feeType: data.feeType,
            otherFee: data.otherFee,
            otherFeePrice: data.otherFeePrice,
            averagePriceList: data.averagePriceList,
            valleylist: data.sectionPriceList
              ? data.sectionPriceList
              : [
                  {
                    rateType: 0,
                    ratePrice: "",
                  },
                  {
                    rateType: 1,
                    ratePrice: "",
                  },
                  {
                    rateType: 2,
                    ratePrice: "",
                  },
                  {
                    rateType: 3,
                    ratePrice: "",
                  },
                ],
            peaklist: data.ladderedPriceList
              ? data.ladderedPriceList.map((item, index) => {
                  return {
                    ladder_data: data.ladderedPriceList[index + 1]
                      ? data.ladderedPriceList[index + 1].ladder
                      : "",
                    price: item.price,
                  };
                })
              : [
                  {
                    ladder: 0,
                    ladder_data: "",
                    price: "",
                  },
                  {
                    ladder: "",
                    ladder_data: "",
                    price: "",
                  },
                ],
          };
        });
      } else {
        this.form = {
          templateType: "1",
          checkList: ["基本费用"],
          templateMode: "1",
          templateType: "1",
          settlementCycle: "",
          settlementTime: "",
          feeType: 1,
          averagePriceList: [
            {
              averageMouth: 1,
              price: "",
            },
            {
              averageMouth: 2,
              price: "",
            },
            {
              averageMouth: 3,
              price: "",
            },
            {
              averageMouth: 4,
              price: "",
            },
            {
              averageMouth: 5,
              price: "",
            },
            {
              averageMouth: 6,
              price: "",
            },
            {
              averageMouth: 7,
              price: "",
            },
            {
              averageMouth: 8,
              price: "",
            },
            {
              averageMouth: 9,
              price: "",
            },
            {
              averageMouth: 10,
              price: "",
            },
            {
              averageMouth: 11,
              price: "",
            },
            {
              averageMouth: 12,
              price: "",
            },
          ], // 月平均价
          valleylist: [
            {
              rateType: 0,
              ratePrice: "",
            },
            {
              rateType: 1,
              ratePrice: "",
            },
            {
              rateType: 2,
              ratePrice: "",
            },
            {
              rateType: 3,
              ratePrice: "",
            },
          ], // 峰谷列表
          peaklist: [
            {
              ladder: 0,
              ladder_data: "",
              price: "",
            },
            {
              ladder: "",
              ladder_data: "",
              price: "",
            },
          ], // 阶梯价格
        };
        if (this.$refs.form) {
          this.$refs.form.clearValidate();
        }
      }
    },
    templateTypeHandler() {
      // 电费 / 水费不同类型对应不同单位
      // 切换不同计费模式及周期
    },
    closeDialog() {
      this.$emit("input", false);
    },
    submitHandle() {
      const { type, form } = this;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let _data = {
            templateName: form.templateName, // 模板名称
            feeType: form.feeType, // 计费模式
            otherFee: form.otherFee, // 其他计费模式
            otherFeePrice: form.otherFeePrice, // 其他计费单价
            settlementCycle: form.settlementCycle,
            settlementTime: form.settlementTime,
            averagePriceList: form.averagePriceList, // 月平均价数据
            sectionPriceList: form.valleylist.map((item) => {
              return {
                rateType: item.rateType,
                ratePrice: item.ratePrice,
              };
            }),
            ladderedPriceList:
              form.feeType === 1
                ? [
                    {
                      ladder: 0,
                      price: form.peaklist[0].price,
                    },
                  ]
                : form.peaklist.map((item, index) => {
                    return {
                      ladder:
                        index === 0 ? 0 : form.peaklist[index - 1].ladder_data,
                      price: item.price,
                    };
                  }),
          };
          if (type === "view") {
            this.$emit("input", false);
          } else if (type === "add") {
            this.submitLoading = true;
            // 提交表单并关闭弹窗
            add(_data)
              .then(() => {
                this.$message({
                  type: "success",
                  message: "新增成功",
                });
                this.$emit("input", false);
                this.onLoad();
                this.submitLoading = false;
              })
              .catch(() => {
                this.submitLoading = false;
              });
          } else {
            this.submitLoading = true;
            add({ ..._data, id: this.ids })
              .then(() => {
                this.$message({
                  type: "success",
                  message: "修改成功",
                });
                this.$emit("input", false);
                this.onLoad();
                this.submitLoading = false;
              })
              .catch(() => {
                this.submitLoading = false;
              });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.price-label {
  font-size: 12px;
  color: red;
  margin: 0;
}
.item-margin {
  margin-bottom: 30px;
}
.ladder-wrapper {
  border: 1px solid #dfdfdf;
  border-radius: 4px;
  font-size: 14px;
  line-height: 1;
  .label-title {
    padding: 10px 20px;
  }
  .label-title:before {
    content: "*";
    color: #f56c6c;
    margin-right: 4px;
  }
  .title-list {
    display: flex;
    background-color: #f0f2f6;
    padding: 10px 0;
    margin-bottom: 16px;
    span {
      flex: 1;
      text-align: center;
    }
  }
}
.flex-wrap-1 {
  padding: 0 10px;
  margin: 0;
}
</style>
